package org.huang.sample12.handler;

import org.huang.sample12.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @描述： 全局的异常处理
 * @作者: Mr.huang
 * @创建时间: 2017/8/31 14:51
 * @版本: 1.0
 */
@ControllerAdvice
//异常处理的顺序也是从具体到一般,如同try...catch....
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger("GlobalExceptionHandler");

    /**
     * 表示 baseErrorHandler 处理 BaseException 异常和其子异常.
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Object baseErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("---BaseException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage());
        return e.getMessage();
    }
    /**
     * 表示 baseErrorHandler 处理 Exception  异常和其子异常.
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        e.printStackTrace();
        logger.error("---DefaultException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage());
        return e.getMessage();
    }
    /**
     * 表示 baseErrorHandler 处理 Exception  异常和其子异常.
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public Object violationExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("---ViolationExceptionHandler Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage());
        ConstraintViolationException exception = (ConstraintViolationException) e;
        //获取校验失败的反馈信息
        List<String> violations = new ArrayList<String>();

        for (ConstraintViolation violation : exception.getConstraintViolations()) {
            violations.add(violation.getMessage());
        }
        Collections.sort(violations);
        return violations.toString();
    }
}
